<template>
  <div class="chat_with" :style="{height: containerHeight + 'px'}">
    <div class="left_aside" :height="containerHeight + 'px'">
      <span class="news_message">
        <svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-bell-fill"></use></svg>
        新消息
      </span>
      <nav>
        <li>
          <el-tooltip class="item" effect="dark" content="好友" placement="right">
            <el-button circle><svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-user"></use></svg></el-button>
          </el-tooltip>
        </li>
        <li>
          <el-tooltip class="item" effect="dark" content="群聊" placement="right">
            <el-button circle><svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-team"></use></svg></el-button>
          </el-tooltip>
        </li>
        <li>
          <el-tooltip class="item" effect="dark" content="设置" placement="right">
            <el-button circle><svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-setting"></use></svg></el-button>
          </el-tooltip>
        </li>
        <li>
          <el-tooltip class="item" effect="dark" content="说明" placement="right">
            <el-button circle><svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-question"></use></svg></el-button>
          </el-tooltip>
        </li>
      </nav>
    </div>
    <div class="right_main">
      <div class="user_list">
        <div class="user_item" :class="activeUser === 0 ? 'active' : ''" @click="activeUser = 0">
          <el-badge is-dot class="item" type="success">
            <img src="../assets/img/user_log.png" alt="">
          </el-badge>
          <div class="text_body">
            <div class="user_name">豆沙包</div>
            <p>
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
            </p>
          </div>
          <div class="time_text">
            <span class="date">10:25AM</span>
            <el-badge :value="12" class="item">
              <span class="mag_number">&nbsp;</span>
            </el-badge>
          </div>
        </div>
        <div class="user_item" :class="activeUser === 1 ? 'active' : ''" @click="activeUser = 0">
          <el-badge is-dot class="item" type="success">
            <img src="../assets/img/user_log.png" alt="">
          </el-badge>
          <div class="text_body">
            <div class="user_name">豆沙包</div>
            <p>
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
            </p>
          </div>
          <div class="time_text">
            <span class="date">10:25AM</span>
            <el-badge :value="12" class="item">
              <span class="mag_number">&nbsp;</span>
            </el-badge>
          </div>
        </div>
        <div class="user_item" :class="activeUser === 2 ? 'active' : ''" @click="activeUser = 0">
          <el-badge is-dot class="item" type="success">
            <img src="../assets/img/user_log.png" alt="">
          </el-badge>
          <div class="text_body">
            <div class="user_name">豆沙包</div>
            <p>
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
              啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
            </p>
          </div>
          <div class="time_text">
            <span class="date">10:25AM</span>
            <el-badge :value="12" class="item">
              <span class="mag_number">&nbsp;</span>
            </el-badge>
          </div>
        </div>
      </div>
      <div class="chat_record">
        <div class="user_item">
          <el-badge is-dot class="item" type="success">
            <img src="../assets/img/user_log.png" alt="">
          </el-badge>
          <div class="text_body">
            <div class="user_name">豆沙包</div>
            <p>在线</p>
          </div>
          <div class="time_text">
            <el-dropdown>
              <el-button type="text">
                <i class="el-icon-more"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>加黑名单</el-dropdown-item>
                <el-dropdown-item>删除好友</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div ref="messageBox" class="chat_record_body">
          <div class="item_text left">
            <div class="p_text ">
              <p>嗨！在吗？我刚刚做了几个新的设计作品，你看看怎么样！</p>
              <span>6:02PM</span>
            </div>
          </div>
          <div class="item_text right">
            <div class="p_text">
              <p>嗨！在吗？我刚刚做了几个新的设计作品，你看看怎么样！</p>
              <span>6:02PM</span>
            </div>
          </div>
        </div>
        <div class="footer_enter" @keyup.enter.native="sendMessage()">
          <el-button type="text">
            <svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-smile"></use></svg>
          </el-button>
          <input class="enter_input" v-model="msgBold" type="text" placeholder="请输入">
          <el-button type="text" @click="sendMessage">
            <svg t="1574134660962" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1908" width="200" height="200"><path d="M0 524.8l281.6 166.4 582.4-531.2L384 704l384 128 256-832zM384 985.6L512 832l-128-64z" fill="#1788EB" p-id="1909"></path></svg>
          </el-button>
          <el-button type="text">
            <svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true"><use xlink:href="#icon-attachment"></use></svg>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapMutations, mapGetters } from 'vuex'
export default {
  name: 'hx-add-user-view',
  components: {},
  data () {
    return {
      toId: '309182426733', // 接收消息的用户ID
      activeUser: 1,
      containerHeight: window.innerHeight - 134 || document.documentElement.clientHeight - 134 || document.body.clientHeight - 134,
      userModules: [
        {
          id: 0,
          icon: 'iconfont icon-message_contact',
          type: 0,
          filter: 'filterMessageUserList',
          current: 'currentMessageInfo'
        },
        {
          id: 1,
          icon: 'iconfont icon-message_Customerservice',
          type: 1,
          filter: 'filterServiceUserList',
          current: 'currentServiceInfo'
        },
        {
          id: 2,
          icon: 'iconfont icon-message_friendlist',
          type: 3,
          filter: 'filterFriendUserList',
          current: 'currentUserInfo'
        }
      ],
      // 客服列表
      customerList: [],
      // 客服列表显示状态
      customerListStatus: false,
      // 左侧搜索框内容
      searchUserKeyWord: null,
      // 左侧搜索框placeholder
      searchUserPlaceholder: 'Contacts',
      // 用户输入的数据
      customerInputMessage: null,
      // 是否显示
      showMessage: false,
      // 当前输入框的消息
      msgBold: null,
      // 创建即时通讯对象
      conn: null,
      // 登录对象
      userAccount: {
        userName: 'hx-103853285458313216' || 'Ebuyhouse',
        password: '123456'
      },
      // 在线用户列表
      OnlineUserList: [],
      // 聊天对象
      CurrentUser: {
        fromName: null
      },
      // 当前用户聊天数据
      // messageList: [],
      // 提示
      TipConfig: {
        isShow: true,
        content: `Interested in this property? Send a message below. Please note, Ebuyhouse staff will never ask you for your account password.`
      },
      isShowHouseInfoBox: false,
      // 是否显示推荐发送消息  // 为true时不可会显示 false时可显示
      isShowHouseInfo: true,
      // 可发送的房源信息
      houseInfoInformation: {
        price: 0
      },
      MyHeaderImg: window.localStorage.getItem('a') || '/static/img/common/header/avatar.png',
      // emoji集合
      EmojiList: [],
      // 是否显示历史记录列表
      isShowHistoryList: false,
      // 历史记录渲染列表
      historyList: [],
      // 历史记录分页配置
      historyPageConfig: {
        pageNum: 1,
        pageSize: 12,
        pageTotal: 0
      },
      // 是否存在用户聊天时
      isNoUser: false,
      // 是否全屏显示
      isFullScreen: false,
      // 存储WEBIM配置
      WebIMConfig: null,
      // 用户信息列表
      userInfoList: [],
      // 聊天数据处理
      // 粘贴板图片处理
      pasteImgList: [],
      // 发送图文本地存储时单独对图片进行处理
      localImgUrlObjct: {},
      // 带过滤的消息列表
      filterMessageUserList: [],
      // 带过滤的客服列表
      filterServiceUserList: [],
      // 带过滤的好友列表
      filterFriendUserList: []
    }
  },
  props: {},
  filters: {
    isShowCardItem (_info) {
      if (_info.ext) {
        if (_info.ext.houseId) {
          console.log(true)
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    }
  },
  watch: {
    userMessageList: {
      handler (_new, _old) {
        this.filterMessageUserList = _new
      },
      immediate: true,
      deep: true
    },
    userFriendList: {
      handler (_new, _old) {
        this.filterFriendUserList = _new
      },
      immediate: true,
      deep: true
    },
    userServiceList: {
      handler (_new, _old) {
        this.filterServiceUserList = _new
      },
      immediate: true,
      deep: true
    },
    friendAll: {
      handler (_new, _old) {
        // 全部好友
        console.log('全部好友或者待添加好友')
        console.log(this.friendAll)
        if (_new.length !== 0) {
          const hxids = [...new Set(_new.map(item => {
            return item.name || item.from
          })), this.globalUserInfo.hxusername].join()
          this.fetchAuthorImgUserName(hxids)
        }
      },
      immediate: true,
      deep: true
    },
    // 监听当前router是否在当前哟用户
    '$route': {
      handler (to, from) {
        if (to.name === 'listing-details') {
          if (to.params) {
            this.isShowHouseInfo = false
            const houseInfos = to.params
            this.fetchHouseInfo(houseInfos.houseId)
          } else {
            this.isShowHouseInfo = true
          }
        } else {
          this.isShowHouseInfo = true
        }
      },
      immediate: true
    },
    // 搜索用户
    searchUserKeyWord (_new, _old) {
      this.filterList(_new)
    },
    token (_new, _old) {
      if (!_new) {
        this.closeMessage()
      }
    },
    messageList: {
      handler (_new, _old) {
        this.scrollBottom()
      },
      deep: true
    },
    messageServiceList: {
      handler (_new, _old) {
        this.scrollBottom()
      },
      deep: true
    }
  },
  methods: {
    ...mapMutations({
      openMessages: 'openMessage',
      UPDATE_CURRENT_USER_MESSAGE_LIST: 'UPDATE_CURRENT_USER_MESSAGE_LIST',
      UPDATE_CURRENT_USER_SERVICE_LIST: 'UPDATE_CURRENT_USER_SERVICE_LIST',
      UPDATE_CURRENT_MESSAGE_INFO: 'UPDATE_CURRENT_MESSAGE_INFO',
      UPDATE_CURRENT_SERVICE_INFO: 'UPDATE_CURRENT_SERVICE_INFO',
      UPDATE_CURRENT_USER_INFO: 'UPDATE_CURRENT_USER_INFO',
      UPDATE_CURRENT_TYPE: 'UPDATE_CURRENT_TYPE',
      UPDATE_USER_PROCESSED_LIST: 'UPDATE_USER_PROCESSED_LIST',
      UPDATE_USER_MESSAGE_LIST: 'UPDATE_USER_MESSAGE_LIST',
      UPDATE_USER_SERVICE_LIST: 'UPDATE_USER_SERVICE_LIST'
    }),
    // 返回选中的对象
    selectObj () {
      return this[this.currentType.current]
    },
    // 过滤指定显示
    filterDesignation (_hxid, _name) {
      // console.log(this.userInfoList)
      let desig = null
      if (this.currentType.type === 1) {
        if (this.userServiceList.length === 0) return ''
        desig = this.userServiceList.filter(item => {
          return _hxid === item.hxusername
        })
        desig = desig.length !== 0 ? desig[0][_name] : ''
      } else {
        if (this.userInfoList.length === 0) return ''
        desig = this.userInfoList.filter(item => {
          return _hxid === item.hxusername
        })
        desig = desig.length !== 0 ? desig[0][_name] : ''
      }
      // if () {}
      return desig
    },
    // 模块红点消息提示
    isModuleSignet (_info) {
      switch (_info.id) {
        case 0:
          return this.userMessageList.some(item => {
            return item.signet
          })
        case 1:
          return this.userServiceList.some(item => {
            return item.signet
          })
        case 2:
          return this.userUnprocessedList.length !== 0
      }
    },
    // 切换模块类型
    switchUserModuleChange (_info) {
      // 更新store
      this.UPDATE_CURRENT_TYPE(_info)
      // 关闭历史记录
      this.switchCloseHistoryWindow()
    },
    // 同意好友请求
    handlerFriendChange (_info) {
      // console.log(_info)
      if (this.token) {
        this.$imConn.subscribed({
          to: _info.from,
          message: '[resp:true]'
        })
        // 需要反向添加对方好友
        this.$imConn.subscribe({
          to: _info.to,
          message: '[resp:true]'
        })
        this.UPDATE_USER_PROCESSED_LIST(Object.assign({}, _info, { type: 'ok' }))
      }
    },
    // 删除好友
    handlerFriendDeleteChange (_info) {
      const _this = this
      _this.$imConn.removeRoster({
        to: _info.name,
        success: function () { // 删除成功
          _this.$imConn.unsubscribed({
            to: _info.name
          })
          _this.$message.success('You have successfully deleted your friend!')
          _this.handlerDesignationDeleteChange(_info.name)
          _this.UPDATE_CURRENT_USER_INFO({})
        },
        error: function () { // 删除失败
          _this.$message.error('Failed to delete!')
        }
      })
    },
    // 通过指定hx-id删除消息列表
    handlerDesignationDeleteChange (_hxid) {
      const cloneUserMessageList = this.userMessageList.filter(item => {
        return item.from !== _hxid
      })
      // 如果当前删除的是正在聊天的
      if (_hxid === this.currentMessageInfo.from) {
        this.UPDATE_CURRENT_MESSAGE_INFO({})
      }
      this.UPDATE_USER_MESSAGE_LIST(cloneUserMessageList)
    },
    // 列表过滤功能
    filterList (_keyword) {
      if (_keyword) {
        // this.currentType
        switch (this.currentType.id) {
          case 0:
            this[this.currentType.filter] = this.userMessageList.filter(item => {
              return this.filterDesignation(item.from, 'nickname').toLowerCase().indexOf(_keyword.toLowerCase()) !== -1
            })
            break
          case 1:
            this[this.currentType.filter] = this.userServiceList.filter(item => {
              return item.accountName.toLowerCase().indexOf(_keyword.toLowerCase()) !== -1
            })
            break
          case 2:
            this[this.currentType.filter] = this.userFriendList.filter(item => {
              console.log(this.filterDesignation(item.name, 'nickname'))
              return this.filterDesignation(item.name, 'nickname').toLowerCase().indexOf(_keyword.toLowerCase()) !== -1
            })
            break
        }
      } else {
        switch (this.currentType.id) {
          case 0:
            this[this.currentType.filter] = this.userMessageList
            break
          case 1:
            this[this.currentType.filter] = this.userServiceList
            break
          case 2:
            this[this.currentType.filter] = this.userFriendList
            break
        }
      }
    },
    // 通过hx-username获取头像以及用户名称
    fetchAuthorImgUserName (_hxids) {
      this.$axios.get(`${this.XT_PROD_PATH}customer/select/hx/user/head`, { params: { hxId: _hxids } })
        .then(res => {
          this.userInfoList = res.data.data
          console.log(this.userInfoList)
        })
    },
    // 选择当前消息进行聊天
    switchMessageChange (_info) {
      // 关闭历史记录
      this.switchCloseHistoryWindow()
      this.UPDATE_CURRENT_MESSAGE_INFO(_info)
      this.scrollBottom()
    },
    // 选择当前客服进行聊天
    switchMessageServiceChange (_info) {
      // 关闭历史记录
      this.switchCloseHistoryWindow()
      this.UPDATE_CURRENT_SERVICE_INFO(_info)
      this.scrollBottom()
    },
    // 选择当前用户进行聊天
    userContactChange () {
      const status = this.userMessageList.filter(item => {
        return item.from === this.currentUserInfo.name
      })
      if (status.length === 0) {
        const creactMessageInfo = Object.assign({}, this.currentUserInfo, { from: this.currentUserInfo.name, to: this.globalUserInfo.hxusername })
        // console.log(creactMessageInfo)
        this.UPDATE_USER_MESSAGE_LIST(creactMessageInfo)
        this.UPDATE_CURRENT_MESSAGE_INFO(creactMessageInfo)
      } else {
        this.UPDATE_CURRENT_MESSAGE_INFO(status[0])
      }
      this.UPDATE_CURRENT_TYPE(this.userModules[0])
    },
    input () {
      const v = this.$refs['execInput'].innerHTML
      this.msgBold = v
    },
    // 粘贴消息到输入框
    paste (e) {
      console.log(e)
      e.preventDefault()
      if (e.clipboardData && e.clipboardData.types) {
        if (e.clipboardData.items.length > 0) {
          if (/^image\/\w+$/.test(e.clipboardData.items[0].type)) {
            const blob = e.clipboardData.items[0].getAsFile()
            const url = window.URL.createObjectURL(blob)
            let insertImg = {}
            insertImg[url] = blob
            this.pasteImgList.push(insertImg)
            // console.log(blob, url)
            document.execCommand('insertImage', false, url)
          }
        }
      }
      // e.preventDefault()
      const html = e.clipboardData.getData('text/html')
      document.execCommand('insertHTML', false, html)
      this.input()
    },
    // 拖拽图片操作
    dragInputChange (e) {
      e.preventDefault()
      console.log(e.dataTransfer)
    },
    // 清除消息输入框
    clearMsg () {
      this.$refs['execInput'].innerHTML = null
    },
    // 初始化Emoji表情
    initEmoji (_WebIM) {
      console.log(_WebIM.Emoji)
      const baseUrl = _WebIM.Emoji.path
      Object.keys(_WebIM.Emoji.map).map((item, index) => {
        this.EmojiList.push({
          id: '1-' + index,
          type: 'img',
          img: baseUrl + _WebIM.Emoji.map[item],
          name: _WebIM.Emoji.map[item],
          emoji: item
        })
      })
      _WebIM.NewEmoji.map.map((item, index) => {
        this.EmojiList.push({
          id: '2-' + index,
          type: 'emoji',
          img: item,
          name: item,
          emoji: item
        })
      })
      console.log(_WebIM.NewEmoji)
    },
    // 格式化发送的数据
    formatToSendMessage (_string) {
      const _this = this
      return _string.replace(/(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]/g, function (params, info) {
        return _this.encodeUnicode(params)
      }).replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, params) {
        console.log(params)
        let handlerString = params
        params.replace(/[^/]+(?=$)/g, function (_params) {
          // console.log(_params)
          _this.EmojiList.map(item => {
            if (item.name === _params) {
              handlerString = item.emoji
            }
          })
        })
        return handlerString
      })
      // return this.encodeUnicode(_string)
    },
    // 格式化本地图片表情转换
    formatLocalImgEmojiToEmoji (_string) {
      const _this = this
      return _string.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, params) {
        // console.log(params)
        let handlerString = params
        params.replace(/[^/]+(?=$)/g, function (_params) {
          // console.log(_params)
          _this.EmojiList.map(item => {
            if (item.name === _params) {
              handlerString = item.emoji
            }
          })
        })
        // console.log(params)
        if (handlerString === params) {
          handlerString = `img:[${handlerString}]`
        }
        return handlerString
      })
    },
    // unicode转码
    encodeUnicode (str) {
      var res = []
      for (var i = 0; i < str.length; i++) {
        res[i] = ('00' + str.charCodeAt(i).toString(16)).slice(-4)
      }
      return '\\u' + res.join('\\u')
    },
    // 格式化返回消息对象参数
    formatMessage (_info, _type) {
      const _this = this
      _info['createTime'] = this.formatTime()
      if (!_type) {
        _info['data'] = _this.formatMessageTxt(_info['data'])
      }
      return _info
    },
    // 格式化返回的表情
    formatMessageTxt (_string) {
      const _this = this
      return _string.replace(/\[.*?\]/g, function (params) {
        const baseUrl = _this.$WebIM.Emoji.path
        if (Object.keys(_this.$WebIM.Emoji.map).includes(params)) {
          return `<img src="${baseUrl + _this.$WebIM.Emoji.map[params]}"/>`
        } else {
          return params
        }
        // console.log(_this.EmojiList.includes(params))
        // console.log(params)
        // console.log(_this.EmojiList.includes(params))
      })
    },
    // 缩放弹窗
    zoomMessage () {
      this.isFullScreen = !this.isFullScreen
      this.customerListStatus = false
      if (this.isFullScreen) {
        window.document.body.style.overflowY = 'hidden'
      } else {
        window.document.body.style.overflowY = 'auto'
      }
    },
    // 关闭弹窗
    closeMessage (e) {
      if (e) {
        e.stopPropagation()
        e.preventDefault()
      }
      // this.conn.close('下线处理')
      window.document.body.style.overflowY = 'auto'
      this.openMessages(false)
    },
    // 格式化时间方法
    formatTime (_timers) {
      // return
      if (_timers) {
        const time = new Date(_timers * 1000)
        return `${time.getHours()}:${time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()}:${time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()} ${time.getMonth() + 1}/${time.getDate()}`
      } else {
        const time = new Date()
        return `${time.getHours()}:${time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()}:${time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()} ${time.getMonth() + 1}/${time.getDate()}`
      }
    },
    // unicodeToUtf8
    unicodeToUtf8 (unicode) {
      unicode = unicode.replace(/\\/g, '%')
      unicode = unescape(unicode)
      unicode = unicode.replace(/%/g, '\\')
      unicode = unicode.replace(/\\/g, '')
      return unicode
    },
    // 如果用户不存在则重新拉取用户列表
    userIsUserList (_msg) {
      let includesStatus = false
      this.OnlineUserList.map(item => {
        // console.log(JSON.stringify(item))
        // console.log(item.fromName)
        // console.log(_msg.from, _msg.to)
        if (item.fromName === _msg.from) {
          includesStatus = true
        }
      })
      if (!includesStatus) {
        // this.filterList()
      }
    },
    // 如果没有处于当前对话消息中 显示提醒红点
    addBadgeChange (_msg) {
      // console.log(this.CurrentUser.fromName, _msg.from)
      if (this.CurrentUser.fromName.toUpperCase() !== _msg.from.toUpperCase()) {
        this.OnlineUserList = this.OnlineUserList.map(item => {
          if (item.fromName.toUpperCase() === _msg.from.toUpperCase()) {
            item['badge']++
          }
          return item
        })
        console.log(this.OnlineUserList)
      } else {
        this.reply(this.CurrentUser.fromUserId)
      }
    },
    // 清除当前红点
    clearBadgeChange () {
      this.OnlineUserList = this.OnlineUserList.map(item => {
        if (item.fromName.toUpperCase() === this.CurrentUser.fromName.toUpperCase()) {
          item['badge'] = 0
          item['messageNum'] = 0
        }
        return item
      })
    },
    // 按住shift+enter发送消息
    shiftAndEnterSend (event) {
      if (event.keyCode === 13 && !event.shiftKey && this[this.currentType.current].from) {
        this.sendMessage()
        event.preventDefault()
        event.stopPropagation()
      }
    },
    // 发送文本消息
    sendMessage () {
      if (!this.msgBold || !(this.msgBold.replace(/&nbsp;|\s/g, ''))) {
        this.$message.info('The content sent cannot be empty')
        return
      }
      if (!this[this.currentType.current].from) {
        this.$message.info('Please select a chat object')
        return
      }
      const _this = this
      const messageContext = this.msgBold
      const filterMsg = _this.sendPasteImg(_this.formatHTML(_this.formatLocalImgEmojiToEmoji(messageContext)))
      console.log('------------------分割线-------------------')
      if (!filterMsg) {
        this.msgBold = null
        this.clearMsg()
        return
      }
      const id = this.$imConn.getUniqueId() // 生成本地消息id
      // eslint-disable-next-line new-cap
      let msg = new this.$WebIM.message('txt', id) // 创建文本消息
      msg.set({
        msg: filterMsg,
        to: _this[_this.currentType.current].from,
        type: 'chat',
        // 消息发送成功回调
        success: function (_id, serverMsgId) {
          _this.scrollBottom()
          if (_this.currentType.id === 0) {
            _this.UPDATE_CURRENT_USER_MESSAGE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.formatMessageTxt(filterMsg) }))
          } else if (_this.currentType.id === 1) {
            _this.UPDATE_CURRENT_USER_SERVICE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.formatMessageTxt(filterMsg) }))
          }
        }
      })
      this.$imConn.send(msg.body)
      this.msgBold = null
      this.clearMsg()
    },
    // 通过id获取图片详细信息
    fetchIdToFile (_fileId) {
      return this.pasteImgList.filter(item => {
        console.log(Object.keys(item))
        // console.log(item)
        return Object.keys(item)[0] === _fileId
      })
    },
    // 查询文本框中是否存在图片 如果是的话则将其转化成贴图消息发送
    sendPasteImg (_msg) {
      const _this = this
      let regImg = /img:\[?(.*?)\].*?/gi
      console.log('获取图片')
      return _msg.replace(regImg, function (match, params) {
        console.log('图片' + params)
        // console.log(_this.fetchIdToFile(params))
        try {
          const imgFile = _this.fetchIdToFile(params)[0]
          var id = _this.$imConn.getUniqueId() // 生成本地消息id
          // eslint-disable-next-line new-cap
          var msg = new _this.$WebIM.message('img', id) // 创建图片消息
          msg.set({
            apiUrl: _this.$WebIM.config.apiURL,
            file: { data: imgFile[params], url: params },
            to: _this[_this.currentType.current].from, // 接收消息对象
            roomType: false,
            onFileUploadError: function (error) {
              console.log(error)
            },
            onFileUploadComplete: function (data) {
              console.log(data)
              // let localFile = {}
              // localFile[]
              _this.localImgUrlObjct[params] = `<img src="${data.uri}/${data.entities[0].uuid}" />`
              console.log('Complete')
            },
            success: function (id) {
              console.log(id)
              console.log('Success')
              _this.scrollBottom()
              if (_this.currentType.id === 0) {
                _this.UPDATE_CURRENT_USER_MESSAGE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.localImgUrlObjct[params] }))
              } else if (_this.currentType.id === 1) {
                _this.UPDATE_CURRENT_USER_SERVICE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.localImgUrlObjct[params] }))
              }
            }
          })
          _this.$imConn.send(msg.body)
          return ''
        } catch (error) {
          return params
        }
      })
      // console.log('结束')
    },
    // 文件包括图片消息回调
    autoSendFileChange (__this, _type) {
      if (!this[this.currentType.current].from) {
        this.$message.info('Please select a chat object')
        return
      }
      // console.log(__this, _type)
      const _this = this
      const id = _this.$imConn.getUniqueId() // 生成本地消息id
      const file = _this.$WebIM.utils.getFileUrl(__this.target)
      // file['file_length'] = file.data.size
      // eslint-disable-next-line new-cap
      let msg = new _this.$WebIM.message(_type, id) // 创建图片消息
      // console.log(_this.$WebIM.utils.getFileUrl(__this.target))
      msg.set({
        apiUrl: _this.$WebIM.config.apiURL,
        file: file,
        to: _this[_this.currentType.current].from, // 接收消息对象
        roomType: false,
        ext: {
          file_length: file.data.size
        },
        onFileUploadError: function () { // 消息上传失败
          console.log('onFileUploadError')
        },
        onFileUploadComplete: function (data) { // 消息上传成功
          console.log('onFileUploadComplete')
          if (_type === 'img') {
            _this.localImgUrlObjct[id] = `<img src="${data.uri}/${data.entities[0].uuid}" />`
          } else if (_type === 'file') {
            _this.localImgUrlObjct[id] = `<a href="${data.uri}/${data.entities[0].uuid}" download="${data.uri}/${data.entities[0].uuid}" style="display: flex; width: 150px; height: 80px; border-radius: 5px; justify-content: center; align-items: center; flex-direction: column; color: #1281fc; background: #fff;"><i class="iconfont icon-nav_article1" style="font-size: 30px"></i><span style="font-size: 14px">Click Me Download File</span></a>`
          } else if (_type === 'audio') {
            _this.localImgUrlObjct[id] = `<audio src="${data.uri}/${data.entities[0].uuid}" controls><source src="${data.uri}/${data.entities[0].uuid}" type="audio/mp3" /></audio>`
          } else if (_type === 'video') {
            _this.localImgUrlObjct[id] = `<video src="${data.uri}/${data.entities[0].uuid}" controls><source src="${data.uri}/${data.entities[0].uuid}" type="video/mp4" /></video>`
          }
        },
        success: function () { // 消息发送成功
          console.log('Success')
          if (_this.currentType.id === 0) {
            _this.UPDATE_CURRENT_USER_MESSAGE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.localImgUrlObjct[id] }))
          } else if (_this.currentType.id === 1) {
            _this.UPDATE_CURRENT_USER_SERVICE_LIST(Object.assign({}, { to: _this[_this.currentType.current].from, from: _this[_this.currentType.current].to, data: _this.localImgUrlObjct[id] }))
          }
          _this.scrollBottom()
          __this.target.value = null
        },
        flashUpload: _this.$WebIM.flashUpload
      })
      _this.$imConn.send(msg.body)
    },
    // 发送房源信息
    sendHouseMessage (_info) {
    },
    // 用户列表-切换用户
    currentUserChange (_info) {
      this.UPDATE_CURRENT_USER_INFO(_info)
    },
    scrollBottom () {
      const _this = this
      setTimeout(() => {
        _this.$refs.messageBox.scrollTop = _this.$refs.messageBox.scrollHeight
      }, 100)
    },
    fetchHouseInfo (_id) {
    },
    openHouseInfo (_info) {
      // this.$router.push({
      //   path: '/listing/details/' + _info.houseId
      // })
      // 关闭当前聊天
      this.closeMessage()
    },
    addEmoji (_emoji) {
      console.log(_emoji)
      if (_emoji.type === 'img') {
        document.execCommand('insertImage', false, _emoji.img)
      } else if (_emoji.type === 'emoji') {
        // debugger
        // this.$refs['execInput'].execCommand('insertText', false, _emoji.emoji)
        // document.execCommand('insertHorizontalRule', false, _emoji.emoji)
        this.$refs['execInput'].innerHTML += _emoji.emoji
        this.msgBold = this.$refs['execInput'].innerHTML
        // document.execCommand('justifyRight')
      }
    },
    // 在线客服列表
    lineServiceChange () {
      let mocker = [
        {
          'accountName': '对方的名字',
          'accountType': 1,
          'createTime': 1548307877000,
          'createUserId': '1',
          'headUrl': 'https://zjcebuyhouse.s3.amazonaws.com/ebuyhouse_images/1547450220133_346.png',
          'hierarchy': '0',
          'hxusername': 'hx-7123456789',
          'id': 1,
          'isActivity': 1,
          'loginType': 1,
          'phone': '1233211100'
        }]
      // this.customerList = res.data.data
      this.UPDATE_USER_SERVICE_LIST(mocker.map(item => {
        item['from'] = item.hxusername
        item['to'] = this.globalUserInfo.hxusername
        item['nickname'] = item.accountName
        return item
      }) || [])
    },
    // 关闭历史记录操作并清空分页数据
    switchCloseHistoryWindow () {
      this.isShowHistoryList = false
      this.historyPageConfig.pageNum = 1
      this.historyPageConfig.pageSize = 12
    },
    // 打开历史纪录操作
    switchOpenHistoryWindow () {
      if (!this.isShowHistoryList && this[this.currentType.current].from) {
        this.fetchHistoryList()
        this.isShowHistoryList = true
      }
    },
    // 获取历史纪录接口
    fetchHistoryList () {
      // select/tourist/all/list
      // CurrentUser
      this.$axios.get(`/////customer/select/hx/chat`, { params: {
        fromId: this[this.currentType.current].to,
        toId: this[this.currentType.current].from,
        pageNum: this.historyPageConfig.pageNum,
        pageSize: this.historyPageConfig.pageSize
        // jId: this.guid
      } })
        .then(res => {
          // console.log(res)
          this.historyList = res.data.data.rows
          this.historyPageConfig.pageTotal = res.data.data.total
        })
    },
    // 跳转指定页面
    jumpHistoryPageContent (_type) {
      const maxPageNum = Math.ceil(this.historyPageConfig.pageTotal / this.historyPageConfig.pageSize)
      switch (_type) {
        case 0:
          if (this.historyPageConfig.pageNum !== 1) {
            this.historyPageConfig.pageNum = 1
            this.fetchHistoryList()
          }
          break
        case 1:
          if (this.historyPageConfig.pageNum > 1) {
            this.historyPageConfig.pageNum--
            this.fetchHistoryList()
          }
          break
        case 2:
          if (this.historyPageConfig.pageNum < maxPageNum) {
            this.historyPageConfig.pageNum++
            this.fetchHistoryList()
          }
          break
        default:
          if (this.historyPageConfig.pageNum !== maxPageNum) {
            this.historyPageConfig.pageNum = maxPageNum
            this.fetchHistoryList()
          }
          break
      }
    },
    // 去除HTML tag
    formatHTML (_string) {
      _string = _string.replace(/<\/?.+?>/g, '')
      _string = _string.replace(/(\n)/g, '')
      _string = _string.replace(/(\t)/g, '')
      _string = _string.replace(/(\r)/g, '')
      _string = _string.replace(/<\/?[^>]*>/g, '')
      _string = _string.replace(/\s/g, ' ')
      _string = _string.replace(/&nbsp;/g, ' ')
      _string = _string.replace(/&rsquo;/g, '’')
      _string = _string.replace(/&lsquo;/g, '‘')
      _string = _string.replace(/&hellip;/g, '…')
      _string = _string.replace(/&ndash;/g, '–')
      _string = _string.replace(/&mdash;/g, '—')
      _string = _string.replace(/&sbquo;/g, '‚')
      _string = _string.replace(/&ldquo;/g, '“')
      _string = _string.replace(/&rdquo;/g, '”')
      _string = _string.replace(/&bdquo;/g, '„')
      _string = _string.replace(/&dagger;/g, '†')
      _string = _string.replace(/&Dagger;/g, '‡')
      _string = _string.replace(/&bull;/g, '•')
      _string = _string.replace(/&permil;/g, '‰')
      _string = _string.replace(/&prime;/g, '′')
      _string = _string.replace(/&Prime;/g, '″')
      _string = _string.replace(/&lsaquo;/g, '‹')
      _string = _string.replace(/&rsaquo;/g, '›')
      _string = _string.replace(/&oline;/g, '‾')
      _string = _string.replace(/&frasl;/g, '⁄')
      console.log(_string)
      return _string
    }
  },
  computed: {
    ...mapGetters({
      token: 'token',
      currentType: 'currentType',
      messageList: 'messageList',
      messageServiceList: 'messageServiceList',
      currentMessageInfo: 'currentMessageInfo',
      currentServiceInfo: 'currentServiceInfo',
      currentUserInfo: 'currentUserInfo',
      userMessageList: 'userMessageList',
      userFriendList: 'userFriendList',
      userServiceList: 'userServiceList',
      userUnprocessedList: 'userUnprocessedList',
      userProcessedList: 'userProcessedList',
      globalUserInfo: 'GlobalUserInfo'
    }),
    friendList: function (params) {
      // console.log([...this.userUnprocessedList, ...this.userProcessedList])
      return [...this.userUnprocessedList, ...this.userProcessedList]
    },
    friendAll: function (params) {
      // console.log([...this.userUnprocessedList, ...this.userProcessedList])
      return [...this.friendList, ...this.userFriendList, ...this.userMessageList]
    }
  },
  created () {
    const that = this
    window.onresize = () => {
      return (() => {
        window.containerHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
        that.containerHeight = window.containerHeight - 134
      })()
    }
  },
  mounted () {
    this.lineServiceChange()
    this.switchUserModuleChange(this.userModules[0])
    this.initEmoji(this.$WebIM)
  },
  destroyed () {
  }
}
</script>
<style lang="scss" scoped>
  .chat_with{
    margin: -20px;
    height: 100%;
    display: flex;
    .left_aside{
      background-color: #E6EBFC;
      width: 120px;
      min-width: 120px;
      height: 100%;
      padding: 10px;
      .news_message{
        width:100%;
        line-height:30px;
        display: block;
        background:rgba(72,128,255,1);
        border-radius:27px;
        text-align: center;
        color: #FFFFFF;
        font-size: 14px;
      }
      nav{
        padding: 20px 0;
        li{
          list-style: none;
          margin-bottom: 30px;
          text-align: center;
          svg{
            color: #999999;
            font-size: 20px;
          }
        }
      }
    }
    .right_main{
      display: flex;
      width: 100%;
      .user_list{
        width: 300px;
        min-width: 300px;
        z-index: 9;
        box-shadow:5px 0px 8px 0px rgba(147, 147, 147, 0.14);
        .user_item{
          width: 100%;
          height: 100px;
          background: #F7F9FC;
          padding: 20px 10px;
          display: flex;
          cursor: pointer;
          border-bottom: 1px solid #efefef;
          img{
            width: 38px;
            height: 38px;
          }
          .text_body{
            padding: 0 10px;
            .user_name{
              font-size: 14px;
              overflow: hidden;
              text-overflow:ellipsis;
              white-space: nowrap;
            }
            p{
              color: #999999;
              font-size: 12px;
              margin: 10px 0;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
            }
          }
          .time_text{
            height: 100%;
            .date{
              margin-bottom: 15px;
              display: block;
            }
            .mag_number{
              width: 35px;
              height: 5px;
              display: block;
            }
          }
        }
        .active{
          background-color: #FFFFFF;
        }
      }
      .chat_record{
        width: 100%;
        position: relative;
        .user_item{
          width: 100%;
          height: 70px;
          background: #FFFFFF;
          padding: 20px;
          display: flex;
          cursor: pointer;
          border-bottom: 1px solid #efefef;
          justify-content: space-between;
          img{
            width: 38px;
            height: 38px;
          }
          .text_body{
            padding: 0 10px;
            width: 85%;
            .user_name{
              font-size: 14px;
              overflow: hidden;
              text-overflow:ellipsis;
              white-space: nowrap;
            }
            p{
              color: #999999;
              font-size: 12px;
              margin: 5px 0;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
            }
          }
        }
        .chat_record_body{
          height: calc(100% - 70px);
          overflow: auto;
          padding: 15px 15px 100px;
          .item_text{
            .p_text{
              padding: 15px 15px 25px 15px;
              border-radius: 20px;
              max-width: 80%;
              display: inline-block;
              position: relative;
              margin-bottom: 35px;
              background:rgba(248,248,248,1);
              box-shadow:0px 2px 5px 0px rgba(147, 147, 147, 0.35);
              p{
                color: #65656F;
                font-size: 14px;
                margin: 0;
              }
              span{
                position: absolute;
                right: 25px;
                bottom: 5px;
                color: #65656F;
                font-size: 14px;
              }
            }
          }
          .left{
            .p_text{
              border-top-left-radius: 0;
            }
          }
          .right{
            text-align: right;
            .p_text{
              background-color: #4880FF;
              border-top-right-radius: 0;
              p,span{
                color: #FFFFFF;
              }
            }
          }
        }
        .footer_enter{
          position: absolute;
          bottom: 0;
          z-index: 8;
          left: 0;
          right: 0;
          height: 60px;
          background-color: #ffffff;
          box-shadow: 0 0 5px rgba(0,0,0,0.1);
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 5px 15px;
          .enter_input{
            width: 80%;
            line-height: 30px;
            border: 0;
          }
          svg{
            font-size: 25px;
          }
          .icon{
            width: 20px;
            height: 20px;
          }
        }
      }
    }
  }
</style>
